package nettcpchat;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient {
    private String host;
    private int port;

    public TCPClient(String host, int port) {
        super();
        this.host = host;
        this.port = port;
        Sender sender = new Sender();
        Thread thread = new Thread(sender);
        thread.start();
    }

    class Sender implements Runnable {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Socket socket = null;
            BufferedReader br = null;
            BufferedWriter bw = null;
            try {
                socket = new Socket(host, port);
                br = new BufferedReader(new InputStreamReader(System.in));
                OutputStream out = socket.getOutputStream();
                bw = new BufferedWriter(new OutputStreamWriter(out));
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println("我说：" + line);
                    bw.write(line);
                    bw.newLine();
                    bw.flush();
                    if ("exit".equals(line)) {
                        break;
                    }
                }
            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    if (br != null) {
                        br.close();
                    }
                    if (bw != null) {
                        bw.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

    }

    public static void main(String[] args) {
        TCPClient tcpClient = new TCPClient("192.168.56.1", 10000);
    }
}
